/**
 * Created by fsj on 2017/6/9.
 */

import Vue from 'vue';

import 'es6-promise/auto';
import axios from 'axios';
import router from 'src/router'
import qs from 'qs';
import SHA256 from 'crypto-js/sha256'

function uncompile(code) {
  code = decodeURI(code);
  var c = String.fromCharCode(code.charCodeAt(0) - code.length);
  for (var i = 1; i < code.length; i++) {
    c += String.fromCharCode(code.charCodeAt(i) - c.charCodeAt(i - 1));
  }
  return c;
}

//axios的一些公共配置和拦截器，比如发送请求显示loading，请求回来loading消失之类的
axios.interceptors.request.use((conf) => {
  conf.auth = {
    username: uncompile('%7B%C3%9C%C3%A1%C3%99%C2%99%C2%90%C3%8F%C3%95%C3%8E%C3%93%C3%A2%C2%A1%5D%60a%5EPca'),
    password: uncompile('%7B%C3%9C%C3%A1%C3%99%C2%99%C2%90%C3%8F%C3%95%C3%8E%C3%93%C3%A2%C2%A1%5D%60a%5EPca')
  };
  return conf;
}, (error) => {
  new Vue({}).$message.error('请求失败');
  return Promise.reject(error);
});

axios.interceptors.response.use((res) => {
  if (res.data.code === 0) {
    return res;
  } else if (res.data.code === 1) {
    new Vue({}).$message.error('请求错误1');
  } else if (res.data.code === 2) {
    new Vue({}).$message.error(res.data.message);
  } else if (res.data.code === 3) {
    router.push('/login');
  } else if (res.data.code === 4) {
    new Vue({}).$message.error('没有权限');
  } else if (res.status == 200) {
    return res;
  } else {
    new Vue({}).$message.error('未知错误');
  }
  return Promise.reject(res);
}, (error) => {
  new Vue({}).$message.error('响应失败');
  return Promise.reject(error);
});

// Vue.prototype.$http = axios;

let ajax = {
  get: (url, params, responseCallback, errorCallback) => {
    axiosRequestParams(url, 'get', params, 10000, responseCallback, errorCallback);
  },
  delete: (url, params, responseCallback, errorCallback) => {
    axiosRequestParams(url, 'delete', params, 10000, responseCallback, errorCallback);
  },
  post: (url, params, responseCallback, errorCallback) => {
    axiosRequestParams(url, 'post', params, 15000, responseCallback, errorCallback);
  },
  put: (url, params, responseCallback, errorCallback) => {
    axiosRequestParams(url, 'put', params, 15000, responseCallback, errorCallback);
  },
  upload: (url, params, responseCallback, errorCallback) => {
    //TODO 上传文件需要特殊处理
    alert('上传文件需要特殊处理');
    axiosRequestParams(url, 'post', params, 0, responseCallback, errorCallback);
  },
  uploadForm: (url, params, responseCallback, errorCallback, formData) => {
    // 处理提交评论的个自定义方法
    axiosRequestParams(url, 'post', params, 0, responseCallback, errorCallback, formData);
  }
};

function axiosRequestParams(url, method, paramsOrData, timeout, responseCallback, errorCallback, formData) {
  let params = {};
  let data = {};
  paramsOrData = paramsOrData || {};
  paramsOrData.httpparams101 = Math.random().toString(36).substr(2);
  let key = '%C2%81%C3%9C%C3%A1%C3%99%C2%99%C2%A5%C3%B1%C3%B3%C2%9BK%5Eggg%C2%99%C3%8A%C3%8A%C3%8A%C3%97%C2%94KMZoq';
  paramsOrData.httpparams102 = SHA256(paramsOrData.httpparams101 + uncompile(key)).toString();
  paramsOrData.accessToken = window.sessionStorage.getItem('myAccessToken');
  paramsOrData.accessUserId = window.sessionStorage.getItem('myUserId');



  if (method === 'get' || method === 'delete' || method === 'head') {
    params = paramsOrData;
    data = {};
  } else {
    params = {};
    data = qs.stringify(paramsOrData);
  }

  // 有formData 走这个；
  if(formData!=null){
    for (let attr in paramsOrData) {
      formData.append(attr,paramsOrData[attr]);
    }
  }

  axiosRequest({
    method: method,
    url: url,
    params: params,
    data: formData ? formData : data,
    timeout: 10000
  }, responseCallback, errorCallback);
}

function axiosRequest(conf, responseCallback, errorCallback) {
  axios({
    method: conf.method || 'get',
    url: conf.url,
    params: conf.params || {},
    data: conf.data,
    timeout: conf.timeout || 10000
  }).then((res) => {
    responseCallback(res.data);
  }).catch((res) => {
    if (errorCallback) {
      errorCallback(res.data);
    }
  });
}

Vue.prototype.$ajax = ajax;
